import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import com.ls.fw.auth.data.bean.User;  
  
public class BeanFactoryAwareBean implements BeanFactoryAware,  
        ApplicationListener<ContextRefreshedEvent> {  
    private DefaultListableBeanFactory beanFactory;  
  
    public void setBeanFactory(BeanFactory beanFactory) throws BeansException {  
        System.out.println("setBeanFactory.........................");  
        this.beanFactory = (DefaultListableBeanFactory) beanFactory;  
    }  
  
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {  
        System.out.println("ContextRefreshed...................");  
  
        BeanDefinitionBuilder userBeanDefinitionBuilder = BeanDefinitionBuilder  
                .genericBeanDefinition(User.class);  
        userBeanDefinitionBuilder.addPropertyValue("username", "chinfeng");  
        userBeanDefinitionBuilder.addPropertyValue("password", "123456");  
        beanFactory.registerBeanDefinition("user",  
                userBeanDefinitionBuilder.getRawBeanDefinition());  
  
        BeanDefinitionBuilder usersBeanDefinitionBuilder = BeanDefinitionBuilder  
                .genericBeanDefinition(User.class);  
        usersBeanDefinitionBuilder.addPropertyReference("user", "user");  
        beanFactory.registerBeanDefinition("userService",  
                usersBeanDefinitionBuilder.getRawBeanDefinition());  
    }  
}  